<link rel="import" href="../../bower_components/polymer/polymer-element.html">
<link rel="import" href="../../bower_components/vaadin-material-theme/vaadin-grid.html">
<link rel="import" href="../../bower_components/vaadin-material-theme/vaadin-grid-selection-column.html">
<link rel="import" href="../view-app.html">
<link rel="import" href="../style/shared-styles.html">

<dom-module id="view-setup-inventory">
    <template>
        <style include="shared-styles app-grid-style flat-button">
             :host {
                margin: 10px;
                display: block;
                --app-grid-columns: 1;
            }
            .btn {
                margin: 20px 10px 0 0;
                width: 250px;
            }
        </style>
        <firebase-auth app-name="smart-mes" id="auth" user="{{user}}"></firebase-auth>
        <firebase-document app-name="smart-mes" id="userData" path="/user/[[user.uid]]" data="{{k}}"></firebase-document>
        <firebase-query app-name="smart-mes" id="notificationQuery" path="/data/[[k.key]]/notificationData"></firebase-query>
        <firebase-query app-name="smart-mes" id="inventoryQuery" path="/data/[[k.key]]/factoryData/inventory" order-by-child="name"
            data="{{inventoryData}}"></firebase-query>
        <firebase-document app-name="smart-mes" id="editInventoryQuery" path="/data/[[k.key]]/factoryData/inventory/[[editKey]]"
            data="{{editInventoryData}}"></firebase-document>
        <app-localstorage-document key="app-lang" data="{{language}}"></app-localstorage-document>
        <ul class="app-grid">
            <li>
                <div class="card" hidden="[[!showAddInventory]]">
                    <h1 class="title">{{localize('add-inventory')}}</h1>
                    <paper-input label="{{localize('name')}}" id="inventoryName" type="text" maxlength="40" auto-validate always-float-label></paper-input>
                    <paper-input label="{{localize('code')}}" id="inventoryCode" type="text" maxlength="20" auto-validate always-float-label></paper-input>
                    <paper-input label="{{localize('cost')}}" id="inventoryCost" type="number" maxlength="9"
                        error-message="Number only" min="0" max="[[maxInput]]" step="0.01" auto-validate always-float-label></paper-input>
                    <paper-input label="{{localize('quantity')}}" id="inventoryQuantity" type="number" maxlength="9"
                        error-message="Number only" min="1" max$="[[maxInput]]" step="0.1" auto-validate always-float-label>
                    </paper-input>
                    <div class="center">
                        <flat-button class="btn" on-click="_openInventoryTable">
                            <button>{{localize('dismiss')}}</button>
                        </flat-button>
                        <flat-button class="btn shamrock" on-click="addInventory">
                            <button disabled$="[[disabled]]">{{localize('add')}}</button>
                        </flat-button>
                    </div>
                </div>
            </li>
            <li>
                <div class="card" hidden="[[!showEditInventory]]">
                    <h1 class="title">{{localize('edit-inventory')}}</h1>
                    <paper-input label="{{localize('name')}}" id="edit_inventoryName" type="text" value="[[editInventoryData.name]]" maxlength="40"
                        auto-validate always-float-label></paper-input>
                    <paper-input label="{{localize('code')}}" id="edit_inventoryCode" type="text" value="[[editInventoryData.code]]" maxlength="20"
                        auto-validate always-float-label></paper-input>
                    <paper-input label="{{localize('cost')}}" id="edit_inventoryCost" type="number" value="[[editInventoryData.cost]]" maxlength="9"
                        auto-validate error-message="Number only" min="0" max="[[maxInput]]" step="0.01" auto-validate always-float-label></paper-input>
                    <paper-input label="{{localize('quantity')}}" id="edit_inventoryQuantity" type="number" value="[[editInventoryData.quantity]]"
                        maxlength="9" error-message="Number only" min="1" max$="[[maxInput]]" step="0.1" auto-validate always-float-label>
                    </paper-input>
                    <div class="center">
                        <flat-button class="btn" on-click="_openInventoryTable">
                            <button>{{localize('dismiss')}}</button>
                        </flat-button>
                        <flat-button class="btn shamrock" on-click="saveInventory">
                            <button disabled$="[[disabled]]">{{localize('save')}}</button>
                        </flat-button>
                    </div>
                </div>
            </li>
            <li>
                <div class="card" hidden="[[!showListInventory]]">
                    <h1 class="title">{{localize('inventory-management')}}</h1>
                    <vaadin-grid id="inventoryTable" aria-label="inventory Management" items="[[inventoryData]]" selected-items="{{selectedItem}}">
                        <vaadin-grid-selection-column flex="1" select-all="{{selectAll}}">
                            <template class="header">
                                <paper-checkbox checked="{{selectAll}}"></paper-checkbox>
                            </template>
                            <template>
                                <paper-checkbox checked="{{selected}}"></paper-checkbox>
                            </template>
                        </vaadin-grid-selection-column>

                        <vaadin-grid-column flex-grow="2" flex="1">
                            <template class="header">
                                <div class="cell">{{localize('name')}}</div>
                            </template>
                            <template>
                                <div class="cell">[[item.name]]</div>
                            </template>
                        </vaadin-grid-column>

                        <vaadin-grid-column flex="1">
                            <template class="header">
                                <div class="cell">{{localize('code')}}</div>
                            </template>
                            <template>
                                <div class="cell">[[item.code]]</div>
                            </template>
                        </vaadin-grid-column>

                        <vaadin-grid-column flex="1">
                            <template class="header">
                                <div class="cell">{{localize('cost')}}</div>
                            </template>
                            <template>
                                <div class="cell">[[item.cost]]</div>
                            </template>
                        </vaadin-grid-column>

                        <vaadin-grid-column flex="1">
                            <template class="header">
                                <div class="cell">{{localize('quantity')}}</div>
                            </template>
                            <template>
                                <div class="cell">[[item.quantity]] {{localize('item')}}</div>
                            </template>
                        </vaadin-grid-column>

                        <vaadin-grid-column flex="1">
                            <template class="header">
                                <div class="cell last">{{localize('edit')}}</div>
                            </template>
                            <template>
                                <div class="cell last">
                                    <paper-icon-button on-click="_openEditInventoryCard" inventory="[[item]]" icon="vaadin:pencil" title="Edit"></paper-icon-button>
                                </div>
                            </template>
                        </vaadin-grid-column>

                        <vaadin-grid-column flex="1">
                            <template class="header">
                                <div class="cell last">{{localize('delete')}}</div>
                            </template>
                            <template>
                                <div class="cell last">
                                    <paper-icon-button on-click="deleteInventory" inventory="[[item]]" icon="vaadin:trash" title="Delete"></paper-icon-button>
                                </div>
                            </template>
                        </vaadin-grid-column>
                    </vaadin-grid>
                    <div class="center">
                        <flat-button class="btn" on-click="_openAddInventoryCard">
                            <button>{{localize('add-inventory')}}</button>
                        </flat-button>
                    </div>
                </div>
            </li>
        </ul>
        <paper-toast id="toastAlert" always-on-top horizontal-align="right" text="{{localize(toastText)}}"></paper-toast>
    </template>
    <script>
        /**
         * @ViewSetupInventory
         * @polymer 
         * @extends {Polymer.Element}
         */
        class ViewSetupInventory extends Polymer.mixinBehaviors([Polymer.AppLocalizeBehavior],
            Polymer.Element) {
            static get is() {
                return 'view-setup-inventory'
            }

            static get properties() {
                return {
                    language: String,
                    editKey: String,
                    inventoryData: {
                        type: Object,
                        notify: true
                    },
                    editInventoryData: Object,
                    selectAll: Boolean,
                    toastText: String,
                    maxInput: {
                        type: Number,
                        value: 999999
                    },
                    disabled: {
                        type: Boolean,
                        value: true
                    },
                    showAddInventory: {
                        type: Boolean,
                        value: false
                    },
                    showEditInventory: {
                        type: Boolean,
                        value: false
                    },
                    showListInventory: {
                        type: Boolean,
                        value: true
                    },
                }
            }

            connectedCallback() {
                super.connectedCallback()
                this.loadResources(this.resolveUrl('../../data/locales.json'))
            }

            ready() {
                super.ready()
                requestAnimationFrame(this._installListeners.bind(this))
            }

            static get observers() {
                return [
                    '_checkInventory(inventoryData)',
                ]
            }

            _installListeners() {
                this.$.inventoryName.addEventListener('input', this._validateInput.bind(this))
                this.$.inventoryCode.addEventListener('input', this._validateInput.bind(this))
                this.$.inventoryCost.addEventListener('input', this._validateInput.bind(this))
                this.$.inventoryQuantity.addEventListener('input', this._validateInput.bind(this))
                this.$.edit_inventoryName.addEventListener('input', this._validateEditInput.bind(this))
                this.$.edit_inventoryCode.addEventListener('input', this._validateEditInput.bind(this))
                this.$.edit_inventoryCost.addEventListener('input', this._validateEditInput.bind(this))
                this.$.edit_inventoryQuantity.addEventListener('input', this._validateEditInput.bind(this))
            }

            _validateInput() {
                const name = this.$.inventoryName.value || 'unname'
                const code = this.$.inventoryCode.value || Math.floor((Math.random() * 1000) + 1)
                const cost = this.$.inventoryCost.value || 0.00
                const quantity = this.$.inventoryQuantity.value || 0
                const decimal = /^(0|[1-9]\d*)(\.\d+)?$/ // alow decimal 2 points
                const integer = /^(0|[1-9]\d*)$/ // alow only positive interger
                if (name && cost && quantity && (cost.match(decimal) || quantity.match(integer)) && cost <= this.maxInput &&
                    (quantity.match(decimal) || quantity.match(integer)) && quantity > 0 && quantity <= this.maxInput) {
                    this.disabled = false
                } else {
                    this.disabled = true
                }
            }

            _validateEditInput() {
                const name = this.$.edit_inventoryName.value || 'unname'
                const code = this.$.edit_inventoryCode.value || Math.floor((Math.random() * 1000) + 1)
                const cost = this.$.edit_inventoryCost.value || 0.00
                const quantity = this.$.edit_inventoryQuantity.value || 0
                const decimal = /^(0|[1-9]\d*)(\.\d+)?$/ // alow decimal 2 points
                const integer = /^(0|[1-9]\d*)$/ // alow only positive interger
                if (name && code && cost && quantity && String(cost).match(decimal) && cost <= this.maxInput &&
                    (quantity.match(decimal) || quantity.match(integer)) && quantity > 0 && quantity <= this.maxInput) {
                    this.disabled = false
                } else {
                    this.disabled = true
                }
            }

            _openEditInventoryCard(e) {
                this.showEditInventory = true;
                this.showListInventory = false;
                const key = e.currentTarget.inventory.$key;
                this.editKey = key;
            }

            _openAddInventoryCard() {
                this.showAddInventory = true;
                this.showListInventory = false;
            }

            _openInventoryTable() {
                this.showListInventory = true;
                this.showAddInventory = false;
                this.showEditInventory = false;
                this._clearField();
            }

            addInventory() {
                const name = this.$.inventoryName.value
                const code = this.$.inventoryCode.value
                const cost = this.$.inventoryCost.value
                const quantity = this.$.inventoryQuantity.value
                const dateTime = Date.now()
                const timestamp = Math.round(Date.now() / 1000)
                if (name && code && cost && quantity) {
                    this.$.inventoryQuery.ref.push({
                        name: name,
                        code: code,
                        cost: parseInt(cost),
                        quantity: parseInt(quantity),
                        add: timestamp,
                        update: timestamp
                    })
                    this._clearField()
                    this.toastText = 'notification-add-successfully'
                    this.$.toastAlert.open()
                    this._openInventoryTable()
                } else {
                    this.toastText = 'notification-error-incomplete-input'
                    this.$.toastAlert.open()
                }
            }

            deleteInventory(e) {
                if (window.confirm("Delete this inventory item ?") == true) {
                    let key = e.currentTarget.inventory.$key
                    this.$.inventoryQuery.ref.child(key).remove()
                    this.toastText = 'notification-delete-successfully'
                    this.$.toastAlert.open()
                }
            }

            saveInventory() {
                const name = this.$.edit_inventoryName.value
                const code = this.$.edit_inventoryCode.value
                const cost = this.$.edit_inventoryCost.value
                const quantity = this.$.edit_inventoryQuantity.value
                const dateTime = Date.now()
                const timestamp = Math.round(Date.now() / 1000)

                if (name && code && cost && quantity) {
                    this.$.editInventoryQuery.ref.update({
                        name: name,
                        code: code,
                        cost: parseInt(cost),
                        quantity: parseInt(quantity),
                        update: timestamp
                    });
                    this.toastText = 'notification-save-successfully'
                    this.$.toastAlert.open()
                    this._openInventoryTable()
                } else {
                    this.toastText = 'notification-error-incomplete-input'
                    this.$.toastAlert.open()
                }
            }

            _checkInventory(data) {
                if (data.length <= 0) return
                let lowInventoryItem = data.filter((i) => i.quantity < 30 && i.quantity > 0).map((obj) => {
                    return obj.code;
                })
                let zeroInventoryItem = data.filter((i) => i.quantity === 0).map((obj) => {
                    return obj.code;
                })
                if (lowInventoryItem.length > 0) {
                    const timestamp = new Date().getTime() / 1000
                    for (let i = 0; i < lowInventoryItem.length; i++) {
                        this.$.notificationQuery.ref.push({
                            created: timestamp,
                            detail: 'Inventory code ' + lowInventoryItem[i] + ' is low stock',
                            type: 'warn'
                        });
                    }
                }
                if (zeroInventoryItem.length > 0) {
                    const timestamp = new Date().getTime() / 1000
                    for (let i = 0; i < zeroInventoryItem.length; i++) {
                        this.$.notificationQuery.ref.push({
                            created: timestamp,
                            detail: 'Inventory code ' + zeroInventoryItem[i] + ' is out of stock.',
                            type: 'critical'
                        });
                    }
                }
                return data;
            }

            _clearField() {
                this.$.inventoryName.value = ""
                this.$.inventoryCode.value = ""
                this.$.inventoryCost.value = ""
                this.$.inventoryQuantity.value = ""
                this.editKey = ""
            }
        }
        customElements.define(ViewSetupInventory.is, ViewSetupInventory)
    </script>
</dom-module>